from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime
import logging

from backend.database import SessionLocal
from backend.models import User
from backend.schemas import UserResponse, UserCreate, UserUpdate

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 路由前缀保持空字符串
router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取所有用户（仅管理员可访问）
@router.get("/api/users", response_model=List[UserResponse])
async def list_users(operator_id: int = Query(...), db: Session = Depends(get_db)):
    operator = db.query(User).filter(User.user_id == operator_id).first()
    if not operator or operator.user_type != "admin":
        raise HTTPException(status_code=403, detail="只限管理员访问")
    users = db.query(User).all()
    logger.info(f"管理员{operator_id}获取用户列表，共{len(users)}条")
    return users

# 获取单个用户详情（仅管理员可访问）
@router.get("/api/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, operator_id: int = Query(...), db: Session = Depends(get_db)):
    operator = db.query(User).filter(User.user_id == operator_id).first()
    if not operator or operator.user_type != "admin":
        raise HTTPException(status_code=403, detail="只限管理员访问")
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    logger.info(f"管理员{operator_id}查询用户{user_id}详情")
    return user

# 创建新用户（仅管理员可访问）
@router.post("/api/users", response_model=UserResponse)
async def create_user(new_user: UserCreate,  db: Session = Depends(get_db)):
    # operator = db.query(User).filter(User.user_id == operator_id).first()
    # if not operator or operator.user_type != "admin":
    #     raise HTTPException(status_code=403, detail="只限管理员访问")
    # 唯一性检查
    if db.query(User).filter(User.username == new_user.username).first():
        raise HTTPException(status_code=400, detail="用户名已存在")
    if db.query(User).filter(User.email == new_user.email).first():
        raise HTTPException(status_code=400, detail="邮箱已注册")
    db_user = User(
        username=new_user.username,
        email=new_user.email,
        user_type=new_user.user_type.value if hasattr(new_user.user_type, 'value') else new_user.user_type,
        password=new_user.password,
        phone=new_user.phone,
        created_at=datetime.utcnow(),
        is_active=True
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    # logger.info(f"管理员{operator_id}创建用户{db_user.user_id}")
    return db_user

# 更新用户信息（仅管理员可访问）
@router.put("/api/users/{user_id}", response_model=UserResponse)
async def update_user(user_id: int, update_data: UserUpdate, operator_id: int = Query(...), db: Session = Depends(get_db)):
    operator = db.query(User).filter(User.user_id == operator_id).first()
    if not operator or operator.user_type != "admin":
        raise HTTPException(status_code=403, detail="只限管理员访问")
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    data = update_data.dict(exclude_unset=True)
    for key, value in data.items():
        setattr(user, key, value)
    db.commit()
    db.refresh(user)
    logger.info(f"管理员{operator_id}更新用户{user_id}")
    return user

# 删除用户（仅管理员可访问）
@router.delete("/api/users/{user_id}")
async def delete_user(user_id: int, operator_id: int = Query(...), db: Session = Depends(get_db)):
    operator = db.query(User).filter(User.user_id == operator_id).first()
    if not operator or operator.user_type != "admin":
        raise HTTPException(status_code=403, detail="只限管理员访问")
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    db.delete(user)
    db.commit()
    logger.info(f"管理员{operator_id}删除用户{user_id}")
    return {"message": "用户已删除"} 